//
//  DMATTManager.m
//  DualMediationSDK
//
//  ATT权限管理器实现 - 独立模块
//

#import "DMATTManager.h"
#import "../AD/Common/DMAdDelegate.h"
#import "../Utils/Logger/IMLogUtils.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import <Foundation/Foundation.h>

#if TARGET_OS_IPHONE
    #import <UIKit/UIKit.h>
#else
    #import <AppKit/AppKit.h>
#endif

// ATT状态常量
static NSString * const kATTStatusKey = @"dm_att_status";

// ATT状态枚举值
typedef NS_ENUM(NSInteger, DMATTStatus) {
    DMATTStatusNotRequired = 0,     // iOS 14以下或不需要
    DMATTStatusNotDetermined = 1,   // 未确定
    DMATTStatusAuthorized = 2,      // 已授权
    DMATTStatusDenied = 3          // 已拒绝
};

@interface DMATTManager ()

@property (nonatomic, strong) dispatch_queue_t attQueue;
@property (nonatomic, assign) DMATTStatus currentATTStatus;

// 私有方法声明
- (void)loadStoredATTStatus;
- (void)saveATTStatus;
- (void)trackATTEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters;
- (void)notifyDelegateOnMainQueue:(void(^)(void))block;

@end

@implementation DMATTManager

+ (instancetype)sharedManager {
    static DMATTManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMATTManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _attQueue = dispatch_queue_create("com.dualmediation.att.queue", DISPATCH_QUEUE_SERIAL);
        _currentATTStatus = DMATTStatusNotDetermined;
        [IMLogUtils info:IMLogTagSDKInit format:@"DMATTManager initialized"];
        [self loadStoredATTStatus];
    }
    return self;
}

#pragma mark - Core API

- (void)requestATTPermissionWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagGeneral format:@"--- Starting ATT Permission Request ---"];
    [self trackATTEvent:@"att_request_start" withParameters:nil];
    
    if (@available(iOS 14, *)) {
        ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
        
        [IMLogUtils info:IMLogTagGeneral format:@"Current ATT status: %ld", (long)status];
        
        switch (status) {
            case ATTrackingManagerAuthorizationStatusNotDetermined: {
                [IMLogUtils info:IMLogTagGeneral format:@"ATT permission not determined, requesting user permission"];
                
                // 通知delegate ATT权限请求即将显示
                [self notifyDelegateOnMainQueue:^{
                    if ([self.delegate respondsToSelector:@selector(dmComplianceManagerWillRequestATTPermission:)]) {
                        [self.delegate dmComplianceManagerWillRequestATTPermission:(id)self];
                    }
                }];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus newStatus) {
                        dispatch_async(self->_attQueue, ^{
                            [IMLogUtils info:IMLogTagGeneral format:@"User ATT permission result: %ld", (long)newStatus];
                            [self trackATTEvent:@"att_request_complete" withParameters:@{@"success": @(YES), @"status": @(newStatus)}];
                            
                            // 更新状态
                            switch (newStatus) {
                                case ATTrackingManagerAuthorizationStatusAuthorized:
                                    self.currentATTStatus = DMATTStatusAuthorized;
                                    break;
                                default:
                                    self.currentATTStatus = DMATTStatusDenied;
                                    break;
                            }
                            
                            [self saveATTStatus];
                            
                            // 通知delegate ATT状态更新
                            [self notifyDelegateOnMainQueue:^{
                                if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didUpdateATTStatus:)]) {
                                    [self.delegate dmComplianceManager:(id)self didUpdateATTStatus:newStatus];
                                }
                            }];
                            
                            if (completion) completion(YES, nil); // ATT结果不影响整体成功状态
                        });
                    }];
                });
                break;
            }
                
            case ATTrackingManagerAuthorizationStatusAuthorized: {
                [IMLogUtils info:IMLogTagGeneral format:@"ATT permission already authorized"];
                self.currentATTStatus = DMATTStatusAuthorized;
                [self saveATTStatus];
                [self trackATTEvent:@"att_request_complete" withParameters:@{@"success": @(YES), @"status": @(status), @"skipped":@(YES)}];
                
                // 通知delegate ATT状态更新
                [self notifyDelegateOnMainQueue:^{
                    if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didUpdateATTStatus:)]) {
                        [self.delegate dmComplianceManager:(id)self didUpdateATTStatus:status];
                    }
                }];
                
                if (completion) completion(YES, nil);
                break;
            }
                
            default: { // Denied or Restricted
                [IMLogUtils info:IMLogTagGeneral format:@"ATT permission denied or restricted"];
                self.currentATTStatus = DMATTStatusDenied;
                [self saveATTStatus];
                [self trackATTEvent:@"att_request_complete" withParameters:@{@"success": @(YES), @"status": @(status), @"skipped":@(YES)}];
                
                // 通知delegate ATT状态更新
                [self notifyDelegateOnMainQueue:^{
                    if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didUpdateATTStatus:)]) {
                        [self.delegate dmComplianceManager:(id)self didUpdateATTStatus:status];
                    }
                }];
                
                if (completion) completion(YES, nil); // ATT被拒绝不阻止SDK运行
                break;
            }
        }
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"iOS version < 14, ATT not required"];
        self.currentATTStatus = DMATTStatusNotRequired;
        [self saveATTStatus];
        [self trackATTEvent:@"att_request_complete" withParameters:@{@"success": @(YES), @"status": @0, @"skipped":@(YES)}];
        
        // 通知delegate ATT状态更新
        [self notifyDelegateOnMainQueue:^{
            if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didUpdateATTStatus:)]) {
                [self.delegate dmComplianceManager:(id)self didUpdateATTStatus:0]; // DMATTStatusNotRequired
            }
        }];
        
        if (completion) completion(YES, nil);
    }
}

- (BOOL)isATTAvailable {
    if (@available(iOS 14, *)) {
        return YES;
    } else {
        return NO;
    }
}

- (NSInteger)getCurrentATTStatus {
    if (@available(iOS 14, *)) {
        return [ATTrackingManager trackingAuthorizationStatus];
    } else {
        return DMATTStatusNotRequired;
    }
}

#pragma mark - Status Properties

- (BOOL)isATTAuthorized {
    if (@available(iOS 14, *)) {
        return [ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusAuthorized;
    } else {
        return NO; // iOS 14以下不需要ATT权限
    }
}

- (BOOL)isATTDenied {
    if (@available(iOS 14, *)) {
        ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
        return status == ATTrackingManagerAuthorizationStatusDenied || status == ATTrackingManagerAuthorizationStatusRestricted;
    } else {
        return NO;
    }
}

- (BOOL)isATTNotDetermined {
    if (@available(iOS 14, *)) {
        return [ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusNotDetermined;
    } else {
        return NO;
    }
}

#pragma mark - 存储和恢复

- (void)loadStoredATTStatus {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.currentATTStatus = [defaults integerForKey:kATTStatusKey];
    
    [IMLogUtils debug:IMLogTagGeneral format:@"Loaded stored ATT status: %ld", (long)self.currentATTStatus];
}

- (void)saveATTStatus {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:self.currentATTStatus forKey:kATTStatusKey];
    [defaults synchronize];
    
    [IMLogUtils debug:IMLogTagGeneral format:@"ATT status saved to persistent storage: %ld", (long)self.currentATTStatus];
}

#pragma mark - 事件追踪和回调

- (void)trackATTEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters {
    [IMLogUtils info:IMLogTagGeneral format:@"ATT Event: %@ - %@", eventName, parameters ?: @"no params"];
    // 这里可以集成具体的事件追踪SDK，如Adjust、Firebase等
}

- (void)notifyDelegateOnMainQueue:(void(^)(void))block {
    if (block) {
        if ([NSThread isMainThread]) {
            block();
        } else {
            dispatch_async(dispatch_get_main_queue(), block);
        }
    }
}

@end